import { isValidExpression } from '@/utils';
import { Modal } from 'antd';
import { SelectBox, TextArea } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { useModel } from 'umi';
import PopupDevComponentsFormalu from './PopdevFormalu';
import { parseFormula } from './server';
// import CpasTableFs from '~/public/cpas-business/cpas-table/CpasTableFs';

const PopupChild = forwardRef(
  ({ IndicatorName, isAudit, saveItem, dataSourceOptions }: any, ref: any) => {
    const { initialState } = useModel('@@initialState');
    const [isFormulaModalOpen, setIsFormulaModalOpen] = useState(false);
    const { dbname, sjnd } = initialState?.curPart;
    const { cpasTableZeroReplace } = initialState?.settings;
    const [CalculationType, setCalculationType] = useState('手动');
    // setCalculationFormulaSystem(rowCalculationFormulaSystem ? rowCalculationFormulaSystem : '');
    const [createTablaRow, setCreateTablaRow] = useState<{
      CalculationFormulaSystem: string;
      itemName: string;
      tip: string;
      action: string;
    }>({ CalculationFormulaSystem: '', itemName: '', tip: '', action: '' });
    const PopupComponentsFormulaRef = useRef<any>();

    const Divstyle: React.CSSProperties = {
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      marginRight: '15px',
    };

    const handleChangeItem = (e: any) => {
      // setValue(e.value);
      setCreateTablaRow({ ...createTablaRow, itemName: e.value });
    };

    const handleChangeFormula = (e: any) => {
      setCreateTablaRow({ ...createTablaRow, CalculationFormulaSystem: e.value });
    };

    const handleChangeTip = (e: any) => {
      setCreateTablaRow({ ...createTablaRow, tip: e.value });
    };
    useImperativeHandle(ref, () => ({
      getCalculationFormulaSystem: () => {
        return createTablaRow;
      },
      showPop: () => {
        setCreateTablaRow({} as any);
        setCalculationType('手动');
        setIsFormulaModalOpen(true);
      },
      closePop: () => {
        setIsFormulaModalOpen(false);
      },
    }));

    const onSelectionData = ({ selectedItem }: any) => {
      // setValue(vValue);
      setCreateTablaRow({ ...createTablaRow, action: selectedItem.displayName });
      setCalculationType(selectedItem.displayName);
      if (selectedItem.displayName === '自动') {
        PopupComponentsFormulaRef.current.show({
          title: '输入公式',
          isAudit: isAudit,
          cancelText: '取消',
          okText: '确定',
          IndicatorName: '',
          rowCalculationFormulaSystem: '',
          // CalculationFormulaSystem: data.CalculationFormula_old_year,
          width: '80%',
          height: '100%',
          okCallback: async (e: any) => {
            // setIsFormulaModalOpen(false);
            handleChangeFormula({ value: e });
          },
          cancelCallback: () => {
            // setIsFormulaModalOpen(false);
            // CalculationFormulaSystemRef.current.initState('');
          },
        });
      }
      // setCreateTabla(selectedItem.displayName);
      // setRealCPASTableRef(selectedItem.displayName, vValue);
    };

    const saveItemCheck = () => {
      debugger;
      if (createTablaRow.itemName.trim() === '') {
        notify('项目名字不能为空', 'error', 2000);
        return false;
      }
      if (
        dataSourceOptions.filter((a: any) => a.IndicatorName === createTablaRow.itemName?.trim())
          .length
      ) {
        notify('项目名字已经存在', 'error', 2000);
        return false;
      }
      const CalculationFormulaSystemRe = createTablaRow.CalculationFormulaSystem.replaceAll(
        '期末_',
        '',
      )
        .replaceAll('期初_', '')
        .replaceAll('本期_', '')
        .replaceAll('上期_', ''); //表名区分跨区间公式，但是字段还是要在存系统公式之前去掉

      if (isValidExpression(createTablaRow.CalculationFormulaSystem) === '合法') {
        saveItem({
          ...createTablaRow,
          CalculationFormulaSystem: CalculationFormulaSystemRe,
          CalculationFormula: parseFormula(createTablaRow.CalculationFormulaSystem).replaceAll(
            '行|标签聚合|合计|',
            '',
          ),
        });
      } else {
        notify(isValidExpression(createTablaRow.CalculationFormulaSystem), 'error', 2000);
      }
    };
    const handleFormulaCancel = () => {
      Modal.destroyAll();
      setIsFormulaModalOpen(false);
    };
    return (
      <>
        <PopupDevComponentsFormalu ref={PopupComponentsFormulaRef} width={800} height={'70%'} />
        <Modal
          zIndex={1002}
          open={isFormulaModalOpen}
          onCancel={handleFormulaCancel}
          onOk={() => saveItemCheck()}
          title={'输入子项目'}
          width={'50vw'}
          maskClosable={false}
          destroyOnClose={true}
        >
          <TextArea
            value={createTablaRow.itemName}
            maxLength={500}
            width={'300'}
            height={'30px'}
            onValueChanged={handleChangeItem} // 输入框内容变化时触发
            // onFocusIn={onFocusInFormula}
            label={`项目名字`}
          />
          <div style={{ display: 'flex', alignItems: 'center', height: '70' }}>
            <TextArea
              value={createTablaRow.CalculationFormulaSystem}
              maxLength={500}
              onValueChanged={handleChangeFormula} // 输入框内容变化时触发
              // onFocusIn={onFocusInFormula}
              label={`系统公式`}
            />
            <div style={Divstyle}>
              <div style={{ marginLeft: '20px', width: '85px' }}>手动/自动 ：</div>
              <SelectBox
                width={120}
                dataSource={[{ displayName: '自动' }, { displayName: '手动' }]}
                displayExpr="displayName"
                valueExpr="displayName"
                value={CalculationType}
                onSelectionChanged={onSelectionData}
                dropDownOptions={{ width: '120px' }}
              />
            </div>
            {/* <Button
              height={'30'}
              style={{ marginLeft: '10px' }}
              onClick={() => {
                setCalculationFormulaSystem('');
              }}
              text="输入公式"
            /> */}
          </div>
          <div className="BalanceLRXJBCRadio">
            {/* <div style={Divstyle}>
              <div style={{ marginLeft: '20px' }}>手动/自动 ：</div>
              <SelectBox
                width={150}
                dataSource={[{ displayName: '自动' }, { displayName: '手动' }]}
                displayExpr="displayName"
                valueExpr="displayName"
                value={createTabla}
                onSelectionChanged={onSelectionData}
                dropDownOptions={{ width: '200px' }}
              />
            </div> */}
            <TextArea
              value={createTablaRow.tip}
              maxLength={500}
              onValueChanged={handleChangeTip} // 输入框内容变化时触发
              // onFocusIn={onFocusInFormula}
              label={`公式提示`}
            />
          </div>
          <div style={{ height: '70%' }} className="tb_capstableContent"></div>
        </Modal>
      </>
    );
  },
);
export default PopupChild;
